package com.fort.teachermanagementsys.springsecurity.service;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fort.teachermanagementsys.mapper.UserMapper;
import com.fort.teachermanagementsys.service.impl.UserServiceImpl;
import com.fort.teachermanagementsys.springsecurity.entity.SelfUserEntity;
import com.fort.teachermanagementsys.entity.User;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;


import java.util.stream.Collectors;

@Component
@Slf4j
public class SelfUserDetailsService implements UserDetailsService {



    private final UserMapper sysUserMapper;
    private final UserServiceImpl userService;

    public SelfUserDetailsService(UserMapper sysUserMapper, UserServiceImpl userService) {
        this.sysUserMapper = sysUserMapper;
        this.userService = userService;
    }
    @Override
    public SelfUserEntity loadUserByUsername(String username) throws UsernameNotFoundException {

//        log.info("2");
        // 查询用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        User user = sysUserMapper.selectOne(queryWrapper.eq("user_name",username));
        if (user != null){

            // 组装参数
            SelfUserEntity selfUserEntity = new SelfUserEntity();
            BeanUtils.copyProperties(user,selfUserEntity);
            selfUserEntity.setAuthorities(userService.getAuthorities(username).stream()
                            .map(o -> o.getRoleName()).collect(Collectors.toList()).stream()
                            .map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
            selfUserEntity.setUsername(user.getUsername());
            return selfUserEntity;
        }else {

            throw new UsernameNotFoundException("用户名不存在~~~");
        }
    }
}
